//
//  EditResumeBasicInfoViewController.m
//  CYWFrame
//
//  Created by 于顺燊 on 2018/9/29.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "EditResumeBasicInfoViewController.h"
#import "BRPickerView.h"
#import "WSDatePickerView.h"

@interface EditResumeBasicInfoViewController ()<UITextFieldDelegate, UITextViewDelegate>

@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) NSString *sexT;
@property (strong, nonatomic) NSString *birthdayStr;
@property (strong, nonatomic) NSString *workDateStr;

@end

@implementation EditResumeBasicInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	[self createUI];
}

- (void)createUI {
	self.view.backgroundColor = UISeparatedColorRGB;
	_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
	[self.view addSubview:_scrollView];
	NSArray *arr = [NSArray arrayWithObjects:@"   姓名*", @"   性别", @"   祖籍", @"   出生年月", @"   所在城市*", @"   详细地址", @"   手机号码*", @"   邮箱*", @"   参加工作时间", @"   一句话介绍自己", nil];
	
	CGSize size = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(15)];
	
	for (int i = 0; i < arr.count; i++) {
		UILabel *label = [[UILabel alloc] init];
		[_scrollView addSubview:label];
		label = [self createLabel:label text:arr[i]];
		label.tag = 1+i;
	}
	
	//姓名
	UILabel *nameL = [self.view viewWithTag:1];
	nameL.frame = CGRectMake(0, 0, SCREEN_WIDTH, size.height+30);
	UITextField *nameTF = [self createTextFieldWith:nameL tag:21 type:0];
	nameTF.text = self.resumeInfo.name;
	
	//性别
	UILabel *sexL = [self.view viewWithTag:2];
	sexL.frame = CGRectMake(0, nameL.y+nameL.height+1, SCREEN_WIDTH, size.height+30);
	
	UIButton *sexBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	[_scrollView addSubview:sexBtn];
	sexBtn.titleLabel.font = kUHSystemFontWithSize(15);
	[sexBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
	sexBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
	
	if ([self.resumeInfo.sex isEqualToString:@"1"]) {
		[sexBtn setTitle:@"男" forState:UIControlStateNormal];
		self.sexT = @"1";
	}
	else {
		[sexBtn setTitle:@"女" forState:UIControlStateNormal];
		self.sexT = @"2";
	}
	sexBtn.frame = CGRectMake(30+size.width, nameL.y+nameL.height+1, SCREEN_WIDTH-30-size.width-SW(20), size.height+30);
	[sexBtn addTarget:self action:@selector(sexAction:) forControlEvents:UIControlEventTouchUpInside];
	sexBtn.tag = 22;
	
	//祖籍
	UILabel *ancestralHomeL = [self.view viewWithTag:3];
	ancestralHomeL.frame = CGRectMake(0, sexL.y+sexL.height+1, SCREEN_WIDTH, size.height+30);
	UITextField *ancestralHomeTF = [self createTextFieldWith:ancestralHomeL tag:23 type:2];
	ancestralHomeTF.text = self.resumeInfo.ancestral_home;
	
	//出生年月
	UILabel *birthdayL = [self.view viewWithTag:4];
	birthdayL.frame = CGRectMake(0, ancestralHomeL.y+ancestralHomeL.height+1, SCREEN_WIDTH, size.height+30);
	UITextField *birthdayTF = [self createTextFieldWith:birthdayL tag:24 type:1];
	self.birthdayStr = self.resumeInfo.birth_date;
	if (self.resumeInfo.birth_date.length >= 8) {
		NSString *yearStr = [self.resumeInfo.birth_date substringWithRange:NSMakeRange(0, 4)];
		NSString *monthStr = [self.resumeInfo.birth_date substringWithRange:NSMakeRange(4, 2)];
		NSString *dayStr = [self.resumeInfo.birth_date substringWithRange:NSMakeRange(6, 2)];
		birthdayTF.text = [NSString stringWithFormat:@"%@年%@月%@日", yearStr, monthStr, dayStr];
	}
	
	//所在城市
	UILabel *cityL = [self.view viewWithTag:5];
	cityL.frame = CGRectMake(0, birthdayL.y+birthdayL.height+1, SCREEN_WIDTH, size.height+30);
	UITextField *cityTF = [self createTextFieldWith:cityL tag:25 type:3];
	cityTF.text = self.resumeInfo.district;
	
	//详细地址
	UILabel *addressL = [self.view viewWithTag:6];
	addressL.frame = CGRectMake(0, cityL.y+cityL.height+1, SCREEN_WIDTH, size.height+30);
	UITextView *addressTV = [self createTextViewWith:addressL tag:26 heightFactor:1.5];
	addressTV.text = self.resumeInfo.address;
	
	//手机号码
	UILabel *phoneL = [self.view viewWithTag:7];
	phoneL.frame = CGRectMake(0, addressTV.y+addressTV.height+1, SCREEN_WIDTH, size.height+30);
	UITextField *phoneTF = [self createTextFieldWith:phoneL tag:27 type:0];
	phoneTF.text = self.resumeInfo.mobile;
	
	//邮箱
	UILabel *emailL = [self.view viewWithTag:8];
	emailL.frame = CGRectMake(0, phoneL.y+phoneL.height+1, SCREEN_WIDTH, size.height+30);
	UITextField *emailTF = [self createTextFieldWith:emailL tag:28 type:0];
	emailTF.text = self.resumeInfo.email;
	
	//参见工作时间
	UILabel *workDateL = [self.view viewWithTag:9];
	workDateL.frame = CGRectMake(0, emailL.y+emailL.height+1, SCREEN_WIDTH, size.height+30);
	UITextField *workDateTF = [self createTextFieldWith:workDateL tag:29 type:4];
	self.workDateStr = self.resumeInfo.work_date;
	if (self.resumeInfo.work_date.length >= 8) {
		NSString *yearStr2 = [self.resumeInfo.work_date substringWithRange:NSMakeRange(0, 4)];
		NSString *monthStr2 = [self.resumeInfo.work_date substringWithRange:NSMakeRange(4, 2)];
		NSString *dayStr2 = [self.resumeInfo.work_date substringWithRange:NSMakeRange(6, 2)];
		workDateTF.text = [NSString stringWithFormat:@"%@年%@月%@日", yearStr2, monthStr2, dayStr2];
	}
	
	//一句话介绍自己
	UILabel *selfIntroL = [self.view viewWithTag:10];
	selfIntroL.frame = CGRectMake(0, workDateL.y+workDateL.height+1, SCREEN_WIDTH, size.height+30);
	UITextView *selfIntroTV = [self createTextViewWith:selfIntroL tag:30 heightFactor:1.5];
	selfIntroTV.text = self.resumeInfo.desc;
	
	//保存按钮
	UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, selfIntroTV.y+selfIntroTV.height+20,  SCREEN_WIDTH-30*2, 40)];
	saveBtn.layer.cornerRadius = saveBtn.height/4;
	[saveBtn setTitle:@"保存" forState:UIControlStateNormal];
	[saveBtn setBackgroundColor:UIMainColorRGB];
	[saveBtn addTarget:self action:@selector(completeAction:) forControlEvents:UIControlEventTouchUpInside];
	[_scrollView addSubview:saveBtn];
	
	_scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, saveBtn.y+saveBtn.height+20);
							  
}

- (UILabel *)createLabel:(UILabel *)label text:(NSString *)text {
	
	label.textColor = [UIColor grayColor];
	label.text = text;
	label.font = kUHSystemFontWithSize(15);
	label.backgroundColor = kWhiteColor;
	return label;
}

- (UITextView *)createTextViewWith:(UILabel *)label tag:(NSInteger)tag heightFactor:(CGFloat)heightFactor
{
	UITextView *textView = [[UITextView alloc] init];
	[_scrollView addSubview:textView];
	textView.textColor = [UIColor lightGrayColor];
	textView.font = kUHSystemFontWithSize(14);
	textView.delegate = self;
	[textView scrollRangeToVisible:NSMakeRange(0,1)];
	CGSize signSize = [textView sizeThatFits:CGSizeMake(SCREEN_WIDTH-20-SW(20), MAXFLOAT)];
	textView.frame = CGRectMake(0, label.y+label.height+1, SCREEN_WIDTH, 15+signSize.height*heightFactor);
	textView.textContainerInset = UIEdgeInsetsMake(15, SW(20), 15, 20);//设置页边
	textView.tag = tag;
	return textView;
}

- (UITextField *)createTextFieldWith:(UILabel *)label tag:(NSInteger)tag type:(NSInteger)type
{
	CGSize size = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(15)];
	UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(30+size.width, label.y, SCREEN_WIDTH-(50+size.width), size.height+30)];
	[_scrollView addSubview:textField];
	textField.delegate = self;
	textField.textColor = kGrayColor;
	textField.clearButtonMode = UITextFieldViewModeWhileEditing;
	textField.font = kUHSystemFontWithSize(15);
	textField.textAlignment = NSTextAlignmentRight;
	textField.rightViewMode = UITextFieldViewModeAlways;
	textField.tag = tag;
	UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.height/2, size.height)];
	textField.rightView = imgV;
	imgV.image = IMAGE(@"arrow_right_grey");
	if (type == 0) {
		return textField;
	}
	else {
		UIView *view = [[UIView alloc] initWithFrame:CGRectMake(textField.x, textField.y, textField.width, textField.height)];
		[_scrollView addSubview:view];
		if(type == 1)
		{
			[view addActionWithblock:^{
				[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
				NSLog(@"选择生日");
				// 显示日期选择
				WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDay CompleteBlock:^(NSDate *selectDate) {
					
					NSString *date = [NSString stringWithFormat:@"%ld年%ld月%ld日",selectDate.year,selectDate.month,selectDate.day];
					textField.text = date;
					self.birthdayStr = [NSString stringWithFormat:@"%ld%02ld%02ld",selectDate.year,selectDate.month,selectDate.day];
				}];
				NSDateFormatter *minDateFormater = [[NSDateFormatter alloc] init];
				[minDateFormater setDateFormat:@"yyyy-MM-dd"];
				NSDate *scrollToDate = [minDateFormater dateFromString:@"1930-1-1"];
				datepicker.minLimitDate = scrollToDate;
				datepicker.maxLimitDate = [NSDate date];
				[datepicker show];
			}];
		}
		else if(type == 2) {
			[view addActionWithblock:^{
				[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
				NSLog(@"选择祖籍");
				//NSArray *defaultSelArr = @[self.resumeInfo.district];
				[BRAddressPickerView showAddressPickerWithShowType:BRAddressPickerModeProvince defaultSelected:nil isAutoSelect:NO themeColor:UIMainColorRGB resultBlock:^(BRProvinceModel *province, BRCityModel *city, BRAreaModel *area) {
					textField.text = province.name;
				} cancelBlock:nil];
			}];
		}
		else if(type == 3) {
			[view addActionWithblock:^{
				[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
				NSLog(@"选择所在城市");
				//NSArray *defaultSelArr = @[self.resumeInfo.district];
				[BRAddressPickerView showAddressPickerWithShowType:BRAddressPickerModeArea defaultSelected:nil isAutoSelect:NO themeColor:UIMainColorRGB resultBlock:^(BRProvinceModel *province, BRCityModel *city, BRAreaModel *area) {
					textField.text = [NSString stringWithFormat:@"%@%@", city.name, area.name];
				} cancelBlock:nil];
			}];
		}
		else if(type == 4) {
			[view addActionWithblock:^{
				[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
				NSLog(@"");
				WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDay CompleteBlock:^(NSDate *selectDate) {
					
					//            NSString *date = [selectDate stringWithFormat:@"yyyy-MM-dd"];
					NSString *date = [NSString stringWithFormat:@"%ld年%ld月%ld日",selectDate.year,selectDate.month,selectDate.day];
					textField.text = date;
					self.workDateStr = [NSString stringWithFormat:@"%ld%02ld%02ld",selectDate.year,selectDate.month,selectDate.day];
				}];
				
				NSDateFormatter *minDateFormater = [[NSDateFormatter alloc] init];
				[minDateFormater setDateFormat:@"yyyy-MM-dd"];
				NSDate *scrollToDate = [minDateFormater dateFromString:@"1930-1-1"];
				datepicker.minLimitDate = scrollToDate;
				datepicker.maxLimitDate = [NSDate date];
				[datepicker show];
			}];
		}
		return textField;
	}
}

- (void)sexAction:(UIButton *)sender {
	NSLog(@"修改性别");
	
	UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改性别" message:nil preferredStyle:UIAlertControllerStyleAlert];
	//    [alert addAction:[UIAlertAction actionWithTitle:@"保密" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
	//        [sender setTitle:@"保密" forState:UIControlStateNormal];
	//        self.sexT = @"0";
	//    }]];
	[alert addAction:[UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
		[sender setTitle:@"男" forState:UIControlStateNormal];
		self.sexT = @"1";
	}]];
	[alert addAction:[UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
		[sender setTitle:@"女" forState:UIControlStateNormal];
		self.sexT = @"2";
	}]];
	[self presentViewController:alert animated:YES completion:nil];
	
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
	if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
		//在这里做你响应return键的代码
		[textView resignFirstResponder];
		return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
	}
	
	return YES;
}
- (void)textViewDidChange:(UITextView *)textView
{
	if (textView.text.length > 30) {
		[self presentViewController:[LZCTools alertMessage:@"不可以超过30字"] animated:YES completion:nil];
		textView.text = [textView.text substringToIndex:30];
		[textView resignFirstResponder];
		return;
	}
	
	[textView flashScrollIndicators];   // 闪动滚动条
	
	//    static CGFloat maxHeight = 130.0f;
	static CGFloat maxHeight = 500.0f;
	CGRect frame = textView.frame;
	CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);
	CGSize size = [textView sizeThatFits:constraintSize];
	if (size.height >= maxHeight)
	{
		size.height = maxHeight;
		textView.scrollEnabled = YES;   // 允许滚动
	}
	else
	{
		textView.scrollEnabled = NO;    // 不允许滚动，当textview的大小足以容纳它的text的时候，需要设置scrollEnabed为NO，否则会出现光标乱滚动的情况
	}
	textView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height);
	
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
	//删除的话string是@“”
	if ([string isEqualToString:@""]){
		return YES;
	}
	
	//string就是此时输入的那个字符textField就是此时正在输入的那个输入框返回YES就是可以改变输入框的值NO相反
	if ([string isEqualToString:@"\n"])  //按会车可以改变
	{
		return YES;
	}
	
	NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
	
	if ([self.view viewWithTag:21] == textField)  //判断是否时我们想要限定的那个输入框
	{
		if ([toBeString length] > 20) { //如果输入框内容大于20则弹出警告
			textField.text = [toBeString substringToIndex:20];
			[self presentViewController:[LZCTools alertMessage:@"名称不可以超过20字"] animated:YES completion:nil];
			return NO;
		}
	}
	if (textField.tag == 27) {
		if (textField.text.length >= 11) {
			return NO;
		}
		return [self validateNumber:string];
	}
	
	return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[textField resignFirstResponder];
	if (textField.text.length == 0) {
		
	}
	return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
	if (textField.tag == 28) {
		if (![self isValidEmail:textField.text]) {
			[LZCTools HUDMessage:@"请输入正确的邮箱" delay:1.0];
			textField.text = @"";
		}
	}
}

- (BOOL)validateNumber:(NSString*)number {
	BOOL res = YES;
	NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
	int i = 0;
	while (i < number.length) {
		NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
		NSRange range = [string rangeOfCharacterFromSet:tmpSet];
		if (range.length == 0) {
			res = NO;
			break;
		}
		i++;
	}
	return res;
}

- (BOOL)isValidEmail:(NSString *)email {
	NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
	NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
	return [emailTest evaluateWithObject:email];
}

- (void)completeAction:(UIButton *)sender {
	NSLog(@"完成信息编辑");
	[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
	
	UITextField *nameTF = (UITextField *)[self.view viewWithTag:21];
	UITextField *ancestralTF = (UITextField *)[self.view viewWithTag:23];
	UITextField *districtTF = (UITextField *)[self.view viewWithTag:25];
	UITextView *addressTV = (UITextView *)[self.view viewWithTag:26];
	UITextField *phoneTF = (UITextField *)[self.view viewWithTag:27];
	UITextField *emailTF = (UITextField *)[self.view viewWithTag:28];
	UITextView *descTV = (UITextView *)[self.view viewWithTag:30];
	
	NSArray *tfArr = @[nameTF, districtTF, phoneTF, emailTF];
	
	for (UITextField *tf in tfArr)
	{
		if ([NSString isEmpty:tf.text]) {
			[self presentViewController:[LZCTools alertMessage:@"带*标识符的为必填项，请填写完成后再提交"] animated:YES completion:nil];
			return;
		}
	}
	
	
	NSDictionary *paramDict = @{
								@"resume_id":self.resumeInfo.resumeId,
								@"title":self.resumeInfo.title,
								@"name":nameTF.text,
								@"head_img":self.resumeInfo.head_img,
								@"sex":self.sexT,
								@"ancestral_home":ancestralTF.text,
								@"category_id":self.resumeInfo.category_id,
								@"salary":self.resumeInfo.salary,
								@"education":self.resumeInfo.education,
								@"mobile":phoneTF.text,
								@"email":emailTF.text,
								@"work_life":self.resumeInfo.work_life,
								@"work_date":self.workDateStr,
								@"district":districtTF.text,
								@"birth_date":self.birthdayStr,
								@"address":addressTV.text,
								@"desc":descTV.text
								};
	
	[[NetworkTool sharedTool] requestWithName:@"创建新简历" URLString:APIUpdateResume parameters:paramDict method:@"POST" callBack:^(id responseObject) {
		NSString *resultState = responseObject[@"data"][@"status"];
		NSString *message = responseObject[@"data"][@"message"];
		if ([resultState integerValue] == 1) {
			UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
			[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
				
				[self.navigationController popViewControllerAnimated:YES];
			}]];
			[self presentViewController:alert animated:YES completion:nil];
		}
		else {
			[self presentViewController:[LZCTools alertMessage:@"您没有修改任何东西"] animated:YES completion:nil];
		}
	}];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
